package com.soilflow.web.controller.common;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.soilflow.common.core.controller.BaseController;
import com.soilflow.common.core.domain.AjaxResult;
import com.soilflow.common.core.page.TableDataInfo;
import com.soilflow.common.enums.BusinessType;
import com.soilflow.common.errorcode.ErrorCode;
import com.soilflow.common.utils.annotation.Log;
import com.soilflow.common.utils.poi.ExcelUtil;
import com.soilflow.system.domain.SysTemplate;
import com.soilflow.system.domain.dto.SysTemplateDto;
import com.soilflow.system.service.SysTemplateService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 模板管理
 * @author soriqe
 * @date 2022/05/26
 */
@RestController
@RequestMapping("/sys/template")
public class SysTemplateController extends BaseController {

    @Resource
    SysTemplateService templateService;
    /**
     * 获取模板列表
     * @param page
     * @return
     */
    @PreAuthorize("@ss.hasPermi('detection:template:list')")
    @GetMapping
    public TableDataInfo list(SysTemplateDto page){
        QueryWrapper<SysTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(page.getDefaultFlag() != null, SysTemplate::getDefaultFlag, page.getDefaultFlag())
                .eq(page.getType() != null, SysTemplate::getType, page.getType())
                .like(page.getName() != null && !page.getName().equals(""), SysTemplate::getName, page.getName())
                .orderByDesc(SysTemplate::getDefaultFlag, SysTemplate::getCreateTime)
                 ;
        startPage();
        List<SysTemplate> list = templateService.list(queryWrapper);
        return getDataTable(list);
    }

    @GetMapping("/type/{type}")
    public AjaxResult allDataByType(@PathVariable Integer type){
        QueryWrapper<SysTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(SysTemplate::getType,type)
                .orderByDesc(SysTemplate::getDefaultFlag, SysTemplate::getUpdateTime)
        ;
        List<SysTemplate> list = templateService.list(queryWrapper);
        return AjaxResult.success(list);
    }


    /**
     * 根据主键id 获取详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id){
        return AjaxResult.success(templateService.getById(id));
    }

    /**
     * 创建模板记录
     * @param template
     * @return
     */
    @PreAuthorize("@ss.hasPermi('detection:template:add')")
    @Log(title = "模板-新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult create(@RequestBody SysTemplate template){
        if (template.getDefaultFlag()){
            QueryWrapper<SysTemplate> checkQueryWrapper = new QueryWrapper<>();
            checkQueryWrapper.lambda()
                    .eq(SysTemplate::getDefaultFlag, true)
                    .eq(SysTemplate::getType, template.getType())
                    .last("limit 1")
            ;
            SysTemplate checkEntity = templateService.getOne(checkQueryWrapper);
            if (checkEntity != null){
                return AjaxResult.error("");
            }
        }
        templateService.save(template);
        return AjaxResult.success();
    }

    /**
     * 修改模板记录
     * @param template
     * @return
     */
    @PreAuthorize("@ss.hasPermi('detection:template:edit')")
    @Log(title = "模板-修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult update(@RequestBody SysTemplate template){
        //校验参数
        if (template.getId() == null){
            return AjaxResult.error(ErrorCode.CommonError.BAD_REQUEST.getMsg());
        }
        //校验数据是否存在
        SysTemplate checkEntity = templateService.getById(template.getId());
        if (checkEntity == null){
            return AjaxResult.error(ErrorCode.CustomerError.DATA_NOT_EXISTS.getMsg());
        }
        //设置模板为默认时，校验是否存在类型相同的模板
        if (template.getDefaultFlag()){
            QueryWrapper<SysTemplate> checkQueryWrapper = new QueryWrapper<>();
            checkQueryWrapper.lambda()
                    .eq(SysTemplate::getDefaultFlag, true)
                    .eq(SysTemplate::getType, template.getType())
                    .last("limit 1")
            ;
            checkEntity = templateService.getOne(checkQueryWrapper);
            if (checkEntity != null && !checkEntity.getId().equals(template.getId())){
                return AjaxResult.error(ErrorCode.CustomerError.DATA_ALREADY_DEFAULT.getMsg());
            }
        }
        templateService.updateById(template);
        return AjaxResult.success();
    }

    /**
     * 修改模板默认标识
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('detection:template:changeDefaultFlag')")
    @Log(title = "模板-修改默认标识", businessType = BusinessType.UPDATE)
    @PutMapping("/defaultFlag/{id}")
    public AjaxResult changeDefaultFlag(@PathVariable Long id){
        SysTemplate checkExistEntity = templateService.getById(id);
        if (checkExistEntity == null){
            return AjaxResult.error(ErrorCode.CustomerError.DATA_NOT_EXISTS.getMsg());
        }
        //将模板的默认状态从true 修改为false 不需要做其他验证
        if (checkExistEntity.getDefaultFlag()){
            checkExistEntity.setDefaultFlag(false);
        }else {
            //校验同一类型下是否存在默认的模板
            QueryWrapper<SysTemplate> checkQueryWrapper = new QueryWrapper<>();
            checkQueryWrapper.lambda()
                    .eq(SysTemplate::getDefaultFlag, true)
                    .eq(SysTemplate::getType, checkExistEntity.getType())
                    .last("limit 1")
            ;
            SysTemplate checkDefaultEntity = templateService.getOne(checkQueryWrapper);
            if (checkDefaultEntity != null && checkDefaultEntity.getId() != checkExistEntity.getId()){
                checkDefaultEntity.setDefaultFlag(false);
                templateService.updateById(checkDefaultEntity);
            }
            //不存在则修改状态
            checkExistEntity.setDefaultFlag(true);
        }
        templateService.updateById(checkExistEntity);
        return AjaxResult.success();
    }

    /**
     * SysTaskEvaluationCriteriaDto模板数据
     */
    @PreAuthorize("@ss.hasPermi('detection:template:export')")
    @Log(title = "模板-导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportExcel(HttpServletResponse response, SysTemplateDto page) {
        QueryWrapper<SysTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(page.getDefaultFlag() != null, SysTemplate::getDefaultFlag, page.getDefaultFlag())
                .eq(page.getType() != null, SysTemplate::getType, page.getType())
                .ge(page.getParams() != null && page.getParams().get("beginTime") != null, SysTemplate::getCreateTime, page.getParams().get("beginTime"))
                .le(page.getParams() != null && page.getParams().get("endTime") != null, SysTemplate::getCreateTime, page.getParams().get("endTime"))
                .like(page.getName() != null && !page.getName().equals(""), SysTemplate::getName, page.getName())
                .orderByAsc(SysTemplate::getType, SysTemplate::getDefaultFlag)
                .orderByDesc(SysTemplate::getUpdateTime)
        ;
        List<SysTemplate> list = templateService.list(queryWrapper);
        for (SysTemplate template : list){
            template.setUrl(page.getClientHostPrefix() + template.getUrl());
        }
        ExcelUtil<SysTemplate> util = new ExcelUtil<SysTemplate>(SysTemplate.class);
        util.exportExcel(response, list, "模板数据");
    }

    /**
     * 删除模板记录
     * @param ids
     * @return
     */
    @PreAuthorize("@ss.hasPermi('detection:template:remove')")
    @Log(title = "模板-删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids){
        templateService.removeByIds(ids);
        return AjaxResult.success();
    }

}
